<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="'测试'"
    @ok="handleSubmit"
    @cancel="handelCancel"
  >
    <AnnoM2m
      ref="AnnoM2mRef"
      v-if="M2moption"
      :data="M2mprops"
      :is-add="M2mIsAdd"
      :option="M2moption"
    ></AnnoM2m>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { BasicModal, useModalInner } from '@/components/Modal';
  import AnnoM2m from './AnnoM2m.vue';
  import { useAppInject } from "@/hooks/web/useAppInject";
  const emit = defineEmits(['success', 'register']);
  const M2mprops = ref<any>(null);
  const M2moption = ref(null);
  const M2mIsAdd = ref(false);
  const AnnoM2mRef = ref<InstanceType<typeof AnnoM2m> | null>(null);
  const { getIsMobile } = useAppInject();

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    const { props, option, isAdd } = data;
    M2mprops.value = toRaw(props);
    M2moption.value = toRaw(option);
    M2mIsAdd.value = toRaw(isAdd);
    setModalProps({
      confirmLoading: false,
      title: (isAdd ? '新增' : '管理') + option.name,
      width: isAdd ? 800 : 920,
      height: 600,
      okText: isAdd ? '关联' : '确认',
      showOkBtn: isAdd,
      defaultFullscreen: getIsMobile.value,
      cancelText: '关闭',
    });

    // resetFields();
    // isUpdate.value = !!data?.isUpdate;
    // if (unref(isUpdate)) {
    //   if (currentState != 'edit') {
    //     resetSchema(props.editSchema);
    //   }
    //   rowId.value = data.record.id;
    //   setFieldsValue({
    //     ...data.record,
    //   });
    //   currentState = 'edit';
    // } else {
    //   if (currentState != 'add') {
    //     resetSchema(props.addSchema);
    //   }
    //   currentState = 'add';
    // }
  });

  // const getTitle = computed(() => (!unref(isUpdate) ? '新增账号' : '编辑账号'));
  function handelCancel() {
    if (M2mIsAdd.value) {
      AnnoM2mRef.value!.clearSelectedRowKeys();
    }
  }
  async function handleSubmit() {
    try {
      if (M2mIsAdd.value) {
        const rows = AnnoM2mRef.value!.getAddRows();
        AnnoM2mRef.value!.clearSelectedRowKeys();
        emit('success', rows);
      }
      // const values = await validate();
      setModalProps({ confirmLoading: true });
      // TODO custom api
      closeModal();
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
